import Config from './config.js'
import Util from './util.js'

export default {
	sendRequest(params) {
		var method = params.method||'GET', // 请求方式
			url = Config.baseUrl + params.url, // 请求路径
			data = {};
		method = method.toUpperCase()
		// if(method=='GET'&&params.data){
		// 	url+="?"
		// 	Object.keys(params.data).forEach((key,index)=>{
		// 		if(index>0) url+="&"
		// 		url+=key+'='+params.data[key]
		// 	})
		// }
		// token
		params.header = params.header||{}
		if (uni.getStorageSync('kqToken')){
			params.header.Authorization='Bearer '+uni.getStorageSync('kqToken')
		} else{
			params.header.Authorization=''
		}
		if(!params.header['content-type']){
			// params.header['content-type']='application/x-www-form-urlencoded;application/json'
			params.header['content-type']='application/json'
		}
		
		// 参数
		if (params.data != undefined) Object.assign(data, params.data);

		if (params.async === false) {
			//同步
			return new Promise((resolve, reject) => {
				uni.request({
					url: url,
					method: method,
					data: data,
					header: params.header,
					dataType: params.dataType || 'json',
					responseType: params.responseType || 'text',
					success: (res) => {
						if (res.data.statusCode == 401) {
							uni.removeStorage({
								key: 'kqToken'
							})
						}
						resolve(res.data);
					},
					fail: (res) => {
						reject(res);
					},
					complete: (res) => {
						reject(res);
					}
				});
			});
		} else {
			console.log('异步')
			//异步
			uni.request({
				url: url,
				method: method,
				data: data,
				header: params.header,
				dataType: params.dataType || 'json',
				responseType: params.responseType || 'text',
				success: (res) => {
					if (res.data.code == 401) {
						uni.removeStorage({
							key: 'jxzhToken'
						})
					}
					typeof params.success == 'function' && params.success(res.data);
				},
				fail: (res) => {
					typeof params.fail == 'function' && params.fail(res);
				},
				complete: (res) => {
					typeof params.complete == 'function' && params.complete(res);
				}
			});
		}
	}
}
